// 引入省市区数据
import { areaList } from '@vant/area-data'; 

Page({
  data: {
    userInfo: {
      avatarUrl: 'https://img.yzcdn.cn/vant/cat.jpeg',
      true_name: '',
      mobile: '',
      email: '',
      sex: 1,
      birthday: '',
      area: '',
      contact_addr: '',
      qq: '',
      telephone: ''
    },
    sexColumns: ['男', '女'],
    sexIndex: 0,
    showSex: false,
    showBirthday: false,
    showArea: false,
    areaList: areaList
  },
  onInputName(e) {
    this.setData({ 'userInfo.true_name': e.detail });
  },
  onInputMobile(e) {
    this.setData({ 'userInfo.mobile': e.detail });
  },
  onInputEmail(e) {
    this.setData({ 'userInfo.email': e.detail });
  },
  onInputAddr(e) {
    this.setData({ 'userInfo.contact_addr': e.detail });
  },
  onInputQQ(e) {
    this.setData({ 'userInfo.qq': e.detail });
  },
  onInputTelephone(e) {
    this.setData({ 'userInfo.telephone': e.detail });
  },
  onChangeAvatar() {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        this.setData({ 'userInfo.avatarUrl': res.tempFilePaths[0] });
      }
    });
  },
  onChooseSex() {
    this.setData({ showSex: true });
  },
  onSexConfirm(e) {
    this.setData({
      'userInfo.sex': e.detail.index + 1,
      showSex: false
    });
  },
  onCloseSex() {
    this.setData({ showSex: false });
  },
  onChooseBirthday() {
    this.setData({ showBirthday: true });
  },
  onBirthdayConfirm(e) {
    this.setData({
      'userInfo.birthday': this.formatDate(e.detail),
      showBirthday: false
    });
  },
  onCloseBirthday() {
    this.setData({ showBirthday: false });
  },
  onChooseArea() {
    this.setData({ showArea: true });
  },
  onAreaConfirm(e) {
    this.setData({
      'userInfo.area': e.detail.values.map(i => i.name).join(' '),
      showArea: false
    });
  },
  onCloseArea() {
    this.setData({ showArea: false });
  },
  onSave() {
    wx.showToast({ title: '保存成功', icon: 'success' });
    setTimeout(() => {
      wx.navigateBack();
    }, 1000);
  },
  // 性别文本
  get sexText() {
    return this.data.userInfo.sex === 1 ? '男' : '女';
  },
  // 日期格式化
  formatDate(dateObj) {
    if (typeof dateObj === 'string') return dateObj;
    const y = dateObj.getFullYear ? dateObj.getFullYear() : dateObj.year;
    const m = (dateObj.getMonth ? dateObj.getMonth() + 1 : dateObj.month).toString().padStart(2, '0');
    const d = (dateObj.getDate ? dateObj.getDate() : dateObj.day).toString().padStart(2, '0');
    return `${y}-${m}-${d}`;
  }
}); 